package com.xhui.vimarket.zkplus.zul.attr.mod.impl;t java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.directwebremoting.util.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Div;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
import org.zkoss.zul.Popup;
import org.zkoss.zul.Span;
import org.zkoss.zul.Textbox;

import com.xhui.crm.common.Constants;
import com.xhui.crm.common.util.string.StrUtil;
import com.xhui.crm.common.vo.RetVO;com.xhui.vimarket.zkplusui.vimarket.zkplus.ui.id.ZKRebcom.xhui.vimarket.zkplusrt com.xhui.vimarket.zkplus.com.xhui.vimarket.zkplusil;
import com.xhui.vimcom.xhui.vimarket.zkplusil.NumUtils;
import comcom.xhui.vimarket.zkpluszkplus.util.ZkUiUtil;
impocom.xhui.vimarket.zkplusarket.zkplus.zul.attr.AttrExt;
import com.com.xhui.vimarket.zkpluskplus.zul.attr.ada.AttrPasswordTwcom.xhui.vimarket.zkpluscom.xhui.vimarket.zkplus.zul.attrcom.xhui.vimarket.zkplus
import com.xhui.vimarket.zkplcom.xhui.vimarket.zkplusn.AttrTmpl;
import com.xhui.vimarket.zkpcom.xhui.vimarket.zkplusan.ValiVo;
import com.xhui.vimarketcom.xhui.vimarket.zkplusr.mod.AttrCompConstants;
import com.xhui.com.xhui.vimarket.zkplus.zul.attr.mod.AttrCompUtil;
import com.xhuicom.xhui.vimarket.zkpluss.zul.attr.rule.AttrValueFromRule;
imporcom.xhui.vimarket.zkplusrket.zkplus.zul.attr.rule.AttrValueLengtcom.xhui.vimarket.zkpluscom.xhui.vimarket.zkplus.zul.attr.rule.AttrValueRexRule;
import cocom.xhui.vimarket.zkplus.zkplus.zul.attr.rule.AttrValueToRule;
import com.xhui.vimarket.zkplus.zul.attr.util.AttrUtil;

/**
 * @版权：福富软件 版权所有 (c) 2010
 * @文件：com.xhui.vimarket.zkplus.zul.attr.mod.impl.AttrPasswordComp.java
 * @所含类：
 * @author: wuyx
 * @version: V1.0
 * @see:
 * @创建日期：2010-12-20
 * @功能说明：属性控件接口
 * @修改记录： =============================================================<br>
 *        日期:2010-12-20 创建
 *        =============================================================<br>
 */
public com.xhui.vimarket.zkplusrPasswordTwoComp extends AttrBaseComp {
    /**
     * TXT_COMPOSER.
     */
    public static final String         PWD_PARENT_BOX_COMPOSER = "com.xhui.vimarket.zkplus.zul.attr.evt.AttrPasswordTwoComposer";
    
    /**
     * ARG_NOT_INIT_PWD.
     */
    public static final String         ARG_NOT_INIT_PWD = "needInit=false";
    /**
     * 
     */
    public static final String         ARG_SHOW_PWD     = "showPwd=true";
    /**
     * 实例.
     */
    private static AttrPasswordTwoComp inst                    = new AttrPasswordTwoComp();
    
    /**
     * 日志.
     */
    private static Logger              logger                  = Logger
                                                                   .getLogger(AttrPasswordTwoComp.class);
   
    
    /**
     * 构造函数. 
     */
    private AttrPasswordTwoComp() {
    }
    
    /**
     * 获取实例.
     * 
     * @return AttrBaseComp
     */
    public static AttrPasswordTwoComp instance() {
        return AttrPasswordTwoComp.inst;
    }
    
    /**
     * 生成组件.
     * 
     * @param attrExt 组件控件
     * @param attrTmpl 组件模板
     * @param comp 显示容器组件
     */
    @SuppressWarnings("deprecation")
    @Override
    public void create(final AttrExt attrExt, final AttrTmpl attrTmpl, final Component comp) {
        super.create(attrExt, attrTmpl, comp);
        // panel
        final Hbox hbox = new Hbox();
        hbox.setAttribute(AttrBaseComp.COMP_MODE, attrTmpl.getDisplayMode());
        hbox.setAttribute(AttrBaseComp.COMP_ATTRID, attrTmpl.getAttrId());
        hbox.setAttribute(AttrBaseComp.COMP_JAVACODE, attrTmpl.getJavaCode());
        hbox.setAttribute(AttrBaseComp.COMP_CANTNULL, AttrCompUtil.getStrCantNull(attrTmpl
            .isCantNull()));
        hbox.setAttribute(AttrBaseComp.COMP_COMP_NAME, attrTmpl.getName());
        if (attrTmpl.getValueLength() > 0) {
            // 由于底层处理有问题，加密后的规则判断有问题，因此要求界面特殊处理
            // 如果有配置 AttrBaseComp.COMP_VALUE_LENGTH 或者  AttrBaseComp.COMP_VALUE_REX 则使用该配置
            // 否则使用param1：长度，param2：正则
            AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_LENGTH, attrTmpl
                .getValueLength());
        } else {
            AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_LENGTH, attrTmpl.getParam1());
        }
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_FROM, attrTmpl.getValueFrom());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_TO, attrTmpl.getValueTo());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_REX, attrTmpl.getValidExpr());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_PARAM1, attrTmpl.getParam1());
        hbox.setWidth("100%");
        hbox.setWidths(this.getWidthsLCT(attrTmpl));
        final Div labDiv = new Div();
        labDiv.setParent(hbox);
        final Label label = new Label(attrTmpl.getName());
        label.setSclass("zp-lt-label");
        /*
        final String sDivboxWithComposer = attrExt.getAttrAda().getAttrTmplCompStr(
            attrTmpl.getDisplayMode(), attrTmpl, attrTmpl.getParam2(), null, null);
        final Div phbox = (Div) Executions.createComponentsDirectly(sDivboxWithComposer, null,
            hbox, null);*/
        /**
         * 默认需要密码初始化功能.
         */
        boolean  isNeedInitPwd = true;
        String compStr = attrTmpl.getParam2();
        String argStr =  null;
        
        if (compStr != null && compStr.indexOf("?") > 0) {
            String[] temp = compStr.split("\\?");
            compStr = temp[0];
            argStr = temp[1];
        } else if (compStr != null && compStr.indexOf("?") == 0) {
            compStr = null;
            argStr = attrTmpl.getParam2();
        }
        if (argStr != null && argStr.indexOf(this.ARG_NOT_INIT_PWD) > -1) {
            isNeedInitPwd = false;
        } else if (argStr != null && argStr.indexOf(ARG_SHOW_PWD) > -1) {
            //add by luxb 2012-5-24 初始化随机密码显示
            AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_ARG, argStr);
        }
  
        final Div phbox = (Div) attrExt.getAttrAda().getAttrTmplCompStr(attrTmpl.getDisplayMode(),
            attrTmpl, compStr, null, null, hbox);
        //phbox.setParent(hbox);
        
        final Textbox textbox = new Textbox();
        //重构Uuid用于压力测试。
        ZKRebuildUuid.rebuildUuidById(textbox, "pw1_"
            + (attrTmpl.getAttrId() > 0 ? attrTmpl.getAttrId()
                : "_" + Math.abs(attrTmpl.getAttrId())));
        textbox.setType("password");
        
        //        final String strWithComposer = attrExt.getAttrAda().getAttrPasswordTextbox2Str(
        //            attrTmpl.getDisplayMode(), attrTmpl, attrTmpl.getParam2(), null, null);
        //        final Textbox textbox2 = (Textbox) Executions.createComponentsDirectly(strWithComposer,
        //            null, null, null);
        final Textbox textbox2 = (Textbox) attrExt.getAttrAda().getAttrPasswordTextbox2Str(
            attrTmpl.getDisplayMode(), attrTmpl, compStr, null, null, null);
        
        //重构Uuid用于压力测试。
        ZKRebuildUuid.rebuildUuidById(textbox2, "pw2_"
            + (attrTmpl.getAttrId() > 0 ? attrTmpl.getAttrId()
                : "_" + Math.abs(attrTmpl.getAttrId())));
        textbox2.setType("password");
        textbox.setWidth("39%");
        textbox2.setWidth("39%");
        textbox2.setStyle("margin-left:2px;display:inline;");
        Span iniDiv = new Span();
        Image iniLab = new Image();
        iniLab.setStyle("margin:0 0 0 4px;display:inline;");
        iniLab.setSrc("/public/images/more_menu.png");
        // iniLab.setTooltiptext("点击工具栏按钮初始化密码");
        iniLab.setParent(iniDiv);
        Popup popup = new Popup();
        popup.setWidth("140px");
        popup.setParent(iniDiv);
        iniDiv.setTooltip(popup);
        Button btnimg = new Button();
        //重构Uuid用于压力测试。
        ZKRebuildUuid.rebuildUuidById(btnimg, "btnimg_"
            + (attrTmpl.getAttrId() > 0 ? attrTmpl.getAttrId()
                : "_" + Math.abs(attrTmpl.getAttrId())));
        // btnimg.setImage(ResConstants.IMG_USER_FIX);
        // btnimg.setStyle("padding:-2px 0 0 -2px;");
        // btnimg.setStyle("height:24px;margin-top:-2px;");
        btnimg.setLabel("初始化密码");
        btnimg.setTooltiptext("点击初始化密码");
        btnimg.addForward(Events.ON_CLICK, phbox, "onInitVal");
        btnimg.addForward(Events.ON_CLICK, phbox, "onResetTetxboxTwo"); // 实时触发事件
        textbox.addForward(Events.ON_FOCUS, phbox, "onResetTetxboxTwo"); // 聚焦选中
        textbox.addForward(Events.ON_BLUR, phbox, "onResetTetxboxTwo");
        textbox2.addForward(Events.ON_FOCUS, phbox, "onResetTetxboxTwo"); // 聚焦选中
        textbox2.addForward(Events.ON_BLUR, phbox, "onTextboxBlur");
        if (attrExt.getAttrAda().isViewMode()) { // 展示模式
            textbox.setReadonly(true);
            textbox2.setReadonly(true);
            btnimg.setVisible(false);
        }
        if (attrTmpl.getHint() != null) {
            hbox.setTooltiptext(attrTmpl.getHint());
        }
        // info
        final Span infDiv = this.createRulebar(attrExt, hbox, attrTmpl);
        // add to zul
        hbox.setParent(comp);
        label.setParent(labDiv);
        infDiv.setParent(labDiv);
        textbox.setParent(phbox);
        textbox2.setParent(phbox);
        iniDiv.setParent(phbox);
        iniDiv.setVisible(isNeedInitPwd);
        btnimg.setParent(popup);
        // toolbox
        this.createToolbox(hbox, attrExt.isToolboxVisible(), attrTmpl);
        // comp log
        if (AttrPasswordTwoComp.logger.isDebugEnabled()) {
            attrExt.appendInnerComp("<hbox width=\"100%\" widths=\"40%,60%\">");
            attrExt.appendInnerCompAttr(AttrBaseComp.COMP_MODE, attrTmpl.getDisplayMode());
            attrExt.appendInnerCompAttr(AttrBaseComp.COMP_ATTRID, "" + attrTmpl.getAttrId());
            attrExt.appendInnerCompAttr(AttrBaseComp.COMP_JAVACODE, "" + attrTmpl.getJavaCode());
            attrExt.appendInnerComp("<label value=\"");
            attrExt.appendInnerComp(attrTmpl.getName());
            attrExt.appendInnerComp("\" />");
            attrExt.appendInnerComp("<textbox type=\"password\" />");
            attrExt.appendInnerComp("</hbox>");
        }
        
        super.afterCreate(attrExt, attrTmpl, comp);
    }
    
    /**
     * 设置值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @param attrInstList 属性实例
     */
    @Override
    public void setValue(final AttrExt attrExt, final Component comp,
        final List<AttrInst> attrInstList,final Map<String, Integer> attrViewMap) {
        super.setValue(attrExt, comp, attrInstList,attrViewMap);
        // 取输入框值
        final Component compTextbox = getTextbox(comp);
        if (compTextbox != null) {
            final long theAttrId = NumUtils
                .toLong("" + comp.getAttribute(AttrBaseComp.COMP_ATTRID));
            final ArrayList<AttrInst> theAttrList = AttrBaseComp.getAttrInstListById(attrInstList,
                theAttrId);
            if (theAttrList.size() > 0) {
                this.setInitValue((Textbox) compTextbox, theAttrList.get(0).getParam1());
                ((Textbox) compTextbox).setValue(theAttrList.get(0).getParam1());
                getTextboxTwo(comp).setValue(theAttrList.get(0).getParam1());
                // javacode回填
                AttrCompUtil.copyTmplInfo(theAttrList.get(0), comp);
            }
        }
    }
    
    /**
     * 获取值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @return ArrayList<AttrInst>
     */
    @Override
    public ArrayList<AttrInst> getValue(final AttrExt attrExt, final Component comp) {
        super.getValue(attrExt, comp);
        final ArrayList<AttrInst> retList = new ArrayList<AttrInst>();
        // 取输入框值
        String val = getAttrPasswordTwoCopmoser(comp).getValue();
        if (!StrUtil.isNullOrEmpty(val)) { // 有填写
            final AttrInst attrInst = attrExt.newAttrInst();
            attrInst.setAttrId(NumUtils.toLong("" + comp.getAttribute(AttrBaseComp.COMP_ATTRID)));
            attrInst.setJavaCode(StrUtil.strnull(comp.getAttribute(AttrBaseComp.COMP_JAVACODE)));
            attrInst.setParam1(val);
       com.xhui.vimarket.zkplusetOp(this.getToolbarOp(comp));
            rcom.xhui.vimarket.zkplusInst);
        }
        return retList;
    }

    /**
     * {@inheritDoc}
     * @see com.xhui.vimarket.zkplus.zul.attr.mod.impl.AttrBaseComp#signRuleHint(com.xhui.vimarket.zkplus.zul.attr.AttrExt, org.zkoss.zk.ui.Component)
     * @author wuyx
     * 2012-2-16 wuyx
     */
    @Override
    public ArrayList<ValiVo> signRuleHint(AttrExt attrExt, Component comp) {
        super.signRuleHint(attrExt, comp);
        if (AttrCompUtil.isCantNull(comp)) { // 必填
            ArrayList<AttrInst> valList = this.getValue(attrExt, comp);
            if (valList == null || valList.size() < 1) {
                ValiVo retVo = new ValiVo();
                ArrayList<ValiVo> retVoList = new ArrayList<ValiVo>();
                retVoList.add(retVo);
                return retVoList;
            }
        }
        return null;
    }
    
    /**
     * 获取原始值.
     * 规则验证用
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @return ArrayList<AttrInst>
     */
    private ArrayList<AttrInst> getRealValue(final AttrExt attrExt, final Component comp) {
        super.getValue(attrExt, comp);
        final ArrayList<AttrInst> retList = new ArrayList<AttrInst>();
        // 取输入框值
        String realVal = getAttrPasswordTwoCopmoser(comp).getRealValue();
        if (!StrUtil.isNullOrEmpty(realVal)) { // 有填写
            final AttrInst attrInst = attrExt.newAttrInst();
            attrInst.setAttrId(NumUtils.toLong("" + comp.getAttribute(AttrBaseComp.COMP_ATTRID)));
            attrInst.setJavaCode(StrUtil.strnull(comp.getAttribute(AttrBaseComp.COMP_JAVACODE)));
            attrInst.setParam1(realVal);
            attrInst.setOp(this.getToolbarOp(comp));
            retList.add(attrInst);
        }
        return retList;
    }
    
    /**
     * 取空值属性实例.
     * 
     * @param attrExt 组件控件
     * @param attrTmpl 模板
     * @return ArrayList<AttrInst>
     */
    @Override
    public ArrayList<AttrInst> getNullValue(final AttrExt attrExt, final AttrTmpl attrTmpl) {
        super.getNullValue(attrExt, attrTmpl);
        final ArrayList<AttrInst> retList = new ArrayList<AttrInst>();
        final AttrInst attrInst = attrExt.newAttrInst();
        attrInst.setAttrId(attrTmpl.getAttrId());
        attrInst.setJavaCode(attrTmpl.getJavaCode());
        retList.add(attrInst);
        return retList;
    }
    
    /**
     * 清空值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     */
    @Override
    public void clean(final AttrExt attrExt, final Component comp) {
        super.clean(attrExt, comp);
        // 取输入框值
        final Component compTextbox = getTextbox(comp);
        if (compTextbox != null) {
            ((Textbox) compTextbox).setText("");
        }
    }
    
    /**
     * getTextbox.
     * 
     * @param root Component
     * @return Textbox
     */
    public static Textbox getTextbox(Component root) {
        // 取输入框
        // hbox // textbox(1) 
        return (Textbox) root.getFirstChild().getNextSibling().getFirstChild();
    }
    
    /**
     * getInitValue.
     * 
     * @param root Component
     * @return String
     * @author wuyx
     * 2011-5-6 wuyx 
     */
    public static String getInitValue(Component root) {
        Textbox textbox = getTextbox(root);
        if (textbox.hasAttribute(AttrBaseComp.COMP_OLD_VAL)) {
            return "" + textbox.getAttribute(AttrBaseComp.COMP_OLD_VAL);
        }
        return null;
    }
    
    /**
     * getInitValue.
     * 
     * @param textbox Textbox
     * @param val String
     * @return String
     * @author wuyx
     * 2011-5-6 wuyx 
     */
    public String setInitValue(Textbox textbox, String val) {
        if (!StrUtil.isNullOrEmpty(val)) {
            textbox.setAttribute(AttrBaseComp.COMP_OLD_VAL, val);
        }
        return null;
    }
    
    /**
     * getTextbox.
     * 
     * @param root Component
     * @return Textbox
     */
    public static Textbox getTextboxTwo(Component root) {
        // 取输入框
        // hbox // textbox(1) 
        return (Textbox) root.getFirstChild().getNextSibling().getFirstChild().getNextSibling();
    }
    
    /**
     * 设置为不允许修改.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @param tflag 设置值，true/false
     */
    @Override
    public void setDisabled(AttrExt attrExt, Component comp, boolean tflag) {
        super.setDisabled(attrExt, comp, tflag);
        ZkUiUtil.setDisabled(comp, tflag);
    }
    
    @Override
    public List<RetVO> validate(AttrExt attrExt, Component comp) {
        ArrayList<AttrInst> realValList = this.getRealValue(attrExt, comp);
        if (realValList == null || realValList.size() < 1) { // 没有值
            if (AttrCompUtil.isCantNull(comp)) { // 需限制不可空
                return AttrCompUtil.getRetVoList(AttrCompConstants.RET_ERROR, AttrCompUtil
                    .getCompName(comp)
                    + AttrCompConstants.STRING_CANT_NULL, comp);
            }
            return null; // 通过
        } else { // 其他规则验证
            // 调用外围的规则验证方法
            AttrPasswordTwoIntf attrPasswordTwoComposer = getAttrPasswordTwoCopmoser(comp);
            RetVO outerRetVo = attrPasswordTwoComposer.validate();
            if (outerRetVo != null && Constants.RET_FALSE.equals(outerRetVo.getResult())) {
                return AttrCompUtil.getRetVoList(AttrCompConstants.RET_ERROR, AttrCompUtil
                    .getCompName(comp)
                    + outerRetVo.getRetMsg(), comp);
            }
            // 如果初始住值和现在值变化过，则验证其他规则了
            String oldVal = getInitValue(comp);
            String newVal = attrPasswordTwoComposer.getValue(); // 保存值
            // String newRealVal = realValList.get(0).getParam1(); // 原始值
            if (!StrUtil.isNullOrEmpty(oldVal) && !oldVal.equals(newVal)) {
                RetVO lengRetVo = AttrValueLengthRule.judgePassword(realValList, comp);
                if (!Constants.RET_TRUE.equals(lengRetVo.getResult())) {
                    return AttrUtil.tranRetVoToOneList(lengRetVo);
                }
                RetVO fromRetVo = AttrValueFromRule.judgePassword(realValList, comp);
                if (!Constants.RET_TRUE.equals(fromRetVo.getResult())) {
                    return AttrUtil.tranRetVoToOneList(fromRetVo);
                }
                RetVO toRetVo = AttrValueToRule.judgePassword(realValList, comp);
                if (!Constants.RET_TRUE.equals(toRetVo.getResult())) {
                    return AttrUtil.tranRetVoToOneList(toRetVo);
                }
                RetVO rexRetVo = AttrValueRexRule.judge(realValList, comp);
                if (!Constants.RET_TRUE.equals(rexRetVo.getResult())) {
                    return AttrUtil.tranRetVoToOneList(rexRetVo);
                }
            }
        }
        return null; // 通过
    }
    
    /**
     * .
     * 
     * @param root Component
     * @return AttrPasswordTwoIntf
     * @author wuyx
     * 2011-5-6 wuyx 
     */
    private AttrPasswordTwoIntf getAttrPasswordTwoCopmoser(Component root) {
        Component hbox = getTextbox(root).gcom.xhui.vimarket.zkplus      AttrPasswordTwoIntf composer = (AttrPasswordTwoIntf) ComposerUtil.getComposer(hbox);
        return composer;
    }
    
    /**
     * {@inheritDoc}
     * @see com.xhui.vimarket.zkplus.zul.attr.mod.AttrComp
     * #getMsgComp(org.zkoss.zk.ui.Component)
     * @author wuyx
     * 2011-7-19 wuyx
     */
    @Override
    public Component getMsgComp(Component comp) {
        return getTextbox(comp);
    }
}
